import axios from 'axios'
import Cookies from 'js-cookie'
import AES from '../common/AES.js'

export const baseUrl = 'https://chentao.mynatapp.cc/invoice'
// export const baseUrl = 'https://www.shangjiatech.com/invoice'
// websock地址 ws http wss https
export const websockUrl = 'wss://chentao.mynatapp.cc/invoice/webs/websocket/'
// export const websockUrl = 'wss://www.shangjiatech.com/invoice/webs/websocket/'



// 请求数据正常状态
export const ERR_OK = 8200
// 页面渲染延时
export const TIME_QUERY = 500
export const imageCDN = process.env.IMAGE_CDN
export const baseImgUrl = process.env.BASE_URL
// 请求超时时间
axios.defaults.timeout = 5000

// 添加请求拦截器
axios.interceptors.request.use((config) => {
  let newTime = new Date().getTime();
  let endTime = sessionStorage.getItem("time")
  var time = newTime - endTime
  // 判断时间是否过期。过期需要重新登录
  if (endTime != null && time > 2 * 60 * 60 * 1000){
    console.log('session过期')
    sessionStorage.removeItem("mailbox");
    sessionStorage.removeItem("record");
    sessionStorage.removeItem("user");
    sessionStorage.removeItem("time");
    window.location.href = '#/login'
  } else {
    // post参数加密 以及过滤文件上传加密
    let type = config.headers['Content-Type']
    if (config.method === 'post' && type.indexOf("multipart/form-data") === -1) {
      let dataInfo = AES.encrypt(config.data)
      config.data = dataInfo
    }
  }
  return config
}, (error) => {
  console.log('http api 错误的传参')
  return Promise.reject(error)
})


// respone拦截器
axios.interceptors.response.use(
  response => {// 回到顶部
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    let sss = AES.decrypt(response.data)
    let data = JSON.parse(sss)
    response.data = data
    let newTime = new Date().getTime();
    sessionStorage.setItem("time", newTime)
    return Promise.resolve(response)
  },
  error => {
    console.log('err' + error)// for debug
    return Promise.reject(error)
  }
)

export function fetch(requestUrl, params = '', method) {
  // const token = Cookies.get('token') === undefined ? '11111' : Cookies.get('token')
  // const token = localStorage.getItem('token') === null ? '' : localStorage.getItem('token')
  return axios({
    url: requestUrl,
    method: method,
    data: JSON.stringify(params),
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    }
  })
}

//文件上传
export function upload(requestUrl, formData){
  return axios({
    url: requestUrl,
    method: 'POST',
    data: formData,
    headers: {
      'Content-Type': "multipart/form-data;boundary="+new Date().getTime(),
    }
  })
}

export function fetchapi(requestUrl, params = '') {
  // const token = Cookies.get('token') === undefined ? '11111' : Cookies.get('token')
  const token = localStorage.getItem('token') === null ? '' : localStorage.getItem('token')
  return axios({
    url: `${baseUrl}api/standardCheck`,
    method: 'post',
    data: {
      'requestId': 'xxxxxx-xxxxxx-xxxxx-xxxxx',
      'apiKey': 'highstore',
      'uri': requestUrl,
      'lang': 'zh-cn',
      'timeZone': '+8:00',
      'sign': ' xxxxxxxxxxxxxxxxxxxxxx',
      'body': params
    },
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'Authorization': token
    }
  })
}

export function getCookies(params) {
  return Cookies.get(params) || ''
}

export function setCookies(memberNo, openid, token) {
  Cookies.set('memberNo', memberNo)
  Cookies.set('openid', openid)
  Cookies.set('token', token)
}

